package com.wocai.jrt.orgadmin.pay.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.common.BigDecimalUtils;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.DoubleEditor;
import com.vteba.web.editer.IntEditor;
import com.vteba.web.editer.LongEditor;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.pay.bean.PaySerialReqBean;
import com.wocai.jrt.orgadmin.pay.bean.PaySerialResBean;
import com.wocai.jrt.orgadmin.pay.model.PaySerial;
import com.wocai.jrt.orgadmin.pay.service.spi.PaySerialService;
import com.wocai.jrt.orgadmin.utils.ExcelUtils;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 支付流水控制器
 * 
 * @author yinlei
 * @date 2015-8-24 10:23:36
 */
@Controller
@RequestMapping("/dailyPay")
public class DailyPayAction extends GenericAction<PaySerial> {
	private static final Logger LOGGER = LoggerFactory.getLogger(DailyPayAction.class);

	@Inject
	private PaySerialService paySerialServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(int.class, new IntEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 获取支付流水页面，仅仅只是页面而已
	 * 
	 * @param model
	 *            参数
	 * @return 产品List
	 */
	@RequestMapping("/list")
	public String list(PaySerialReqBean model) {
		return "pay/daily-list";
	}

	/**
	 * 产品页面发起的产品查询请求，返回的是列表
	 * 
	 * @param model
	 *            参数
	 * @return 意见反馈List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody PaySerialReqBean model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request PaySerialResBean query, param = [{}]", JSON.toJSONString(model));

			Table table = queryDaily(model);

			int size = table.getAllSize();
			map.put("aaData", table.getList()); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request PaySerialResBean query error, msg = [{}]", e.getMessage());
		}

		return map;
	}
	
	/**
	 * 产品页面发起的产品查询请求，返回的是列表
	 * @param model
	 *            参数
	 * @return 
	 */
	@ResponseBody
	@RequestMapping("/confirm")
	public JsonBean confirm(@RequestBody PaySerialReqBean model) {
		JsonBean  bean = new JsonBean();
		try {
			LOGGER.info("request PaySerialResBean confirm, param = [{}]", JSON.toJSONString(model));
			if(StringUtils.isBlank(model.getId())){
				bean.setCode(0);
				bean.setMessage("request PaySerialResBean confirm param id is null");
				LOGGER.error("request PaySerialResBean confirm param id is null");
				return bean;
			}
			PaySerial paySerial = new PaySerial();
			paySerial.setId(model.getId());
			paySerial.setAuditId(UserUtils.getUserId());
			paySerial.setAuditTime(new Date());
			paySerial.setAuditState(1);
			int result = paySerialServiceImpl.updateById(paySerial);
			if(result == 1){
				bean.setCode(1);
				bean.setMessage("确认清算成功.");
			}else{
				bean.setCode(0);
				bean.setMessage("确认清算失败.");
			}
		}catch (Exception e) {
			LOGGER.error("request PaySerialResBean confirm error, msg = [{}]", e.getMessage());
			bean.setCode(0);
			bean.setMessage("确认清算失败.");
		}
		return bean;
	}
	
	/**
	 * 产品页面发起的产品查询请求，返回的是列表
	 * 
	 * @param model
	 *            参数
	 * @return 意见反馈List
	 */
	@ResponseBody
	@RequestMapping("/export")
	public JsonBean export(PaySerialReqBean model, HttpServletResponse response) {
		JsonBean jsonBean = new JsonBean();

		try {
			LOGGER.info("request export, param = [{}]", JSON.toJSONString(model));

			model.setPageSize(-1);
			Table table = queryDaily(model);

			String excelPath = ExcelUtils.exportExcel(table.getList());
			MyFileUtils.downloadFile(excelPath, response);

			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS);

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("export failure");
			LOGGER.error("request PaySerialResBean query error, msg = [{}]", e.getMessage());
		}

		return jsonBean;
	}

	private Table queryDaily(PaySerialReqBean model) {
		model.setState(1);
		model.setOrgId(UserUtils.getUser().getOrgId());

		if (model.getType() == 0) {
			if (null != model.getPayStartTime()) {
				model.setPayEndTime(new DateTime(model.getPayStartTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}
		} else {
			if (null != model.getPayEndTime()) {
				model.setPayEndTime(new DateTime(model.getPayEndTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}

			if (null != model.getOrderEndTime()) {
				model.setOrderEndTime(new DateTime(model.getOrderEndTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}
		}

		int size = paySerialServiceImpl.fetchCount(model);
		if (model.getPageSize() == -1) {
			model.setStart(null);
		}

		List<PaySerialResBean> list = new ArrayList<PaySerialResBean>();

		if (size > 0) {
			list = paySerialServiceImpl.fetchPaySerial(model);
			LOGGER.info("query PaySerialResBean list success, size = [{}]", list.size());

			for (PaySerialResBean psrb : list) {
				double posHandleFee = BigDecimalUtils.multiply(psrb.getPayAmount(), 1.25 / 100);

				posHandleFee = posHandleFee >= 80 ? 80 : posHandleFee;
				psrb.setPosHandleFee(posHandleFee);
				psrb.setWithdrawAmount(BigDecimalUtils.subtract(psrb.getPayAmount(), posHandleFee));
			}
		}

		Table table = new Table();
		table.setList(list);
		table.setAllSize(size);

		return table;
	}

	class Table {
		private List<PaySerialResBean> list;
		private int allSize;

		public List<PaySerialResBean> getList() {
			return list;
		}

		public void setList(List<PaySerialResBean> list) {
			this.list = list;
		}

		public int getAllSize() {
			return allSize;
		}

		public void setAllSize(int allSize) {
			this.allSize = allSize;
		}

	}

}
